<script setup>
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAttractionApi } from '@/api/attraction/index'

const router = useRouter()

// 状态管理
const attractionFormRef = ref()
const attractionApi = useAttractionApi()
const state = reactive({
  loading: false,
  pageIndex: 1,
  pageSize: 6,
  page: {
    records: [],
    total: 0
  },
  searchParams: {
    name: '',
    address: '',
    status: undefined
  },
  selectionIds: [],

  showEdit: false,
  dialogTitle: '',
  attractionForm: {
    id: undefined,
    name: '',
    imageUrl: '',
    address: '',
    description: '',
    status: 0
  },
  attractionRules: {
    name: [{ required: true, message: '请输入景点名称', trigger: 'blur' }],
    imageUrl: [{ required: true, message: '请输入景点图片', trigger: 'blur' }],
    address: [{ required: true, message: '请输入景点地址', trigger: 'blur' }]
  },
  fileUploadApi: '/api/file/upload',
  fileHeaders: {
    Authorization: sessionStorage.getItem('token')
  }
})

// 获取表格数据
const getTableData = async (current = 1) => {
  try {
    state.loading = true
    state.pageIndex = current
    const params = { pageIndex: state.pageIndex, pageSize: state.pageSize }
    state.page = await attractionApi.getPage(params, state.searchParams)
  } finally {
    state.loading = false
  }
}

// 处理每页大小改变
const handleSizeChange = async (val) => {
  state.pageSize = val
  await getTableData()
}

// 处理复选框选中
const handleSelectionChange = (rows) => {
  state.selectionIds = rows.map((v) => v.id)
}

// 重置搜索
const resetSearch = () => {
  state.searchParams = {
    name: '',
    address: '',
    status: undefined
  }
  getTableData()
}

// 打开编辑弹窗
const openEdit = (row) => {
  state.showEdit = true
  state.dialogTitle = '添加景点'
  if (row) {
    state.dialogTitle = '修改景点'
    state.attractionForm = { ...row }
  }
}

// 关闭编辑弹窗
const handleClose = () => {
  attractionFormRef.value.resetFields()
}

// 上传前
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('上传头像图片只能是图片格式!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('上传头像图片大小不能超过 10MB!')
    return false
  }

  return isImage && isLt10M
}

// 上传成功
const handleSuccess = (res, file) => {
  if (res.code === 200) {
    state.attractionForm.imageUrl = res.data
  } else {
    ElMessage.error(res.message || '头像上传失败')
  }
}

// 处理提交
const handleSubmit = async () => {
  attractionFormRef.value.validate(async (valid) => {
    if (valid) {
      if (state.attractionForm.id) {
        await attractionApi.update(state.attractionForm)
      } else {
        await attractionApi.save(state.attractionForm)
      }
      state.showEdit = false
      ElMessage.success('操作成功')
      await getTableData()
    }
  })
}

// 处理删除
const handleRemove = (ids) => {
  ElMessageBox.confirm('确认要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await attractionApi.remove(ids)
    ElMessage.success('删除成功')
    await getTableData()
  })
}

// 初始化加载景点
onMounted(() => {
  getTableData()
})
</script>

<template>
  <el-card>
    <el-form :model="state.searchParams" :inline="true">
      <el-row>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="景点名称" prop="name">
            <el-input v-model="state.searchParams.name" placeholder="请输入景点名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="景点地址" prop="address">
            <el-input v-model="state.searchParams.address" placeholder="请输入景点地址" clearable />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="景点状态" prop="status">
            <el-select v-model="state.searchParams.status" clearable placeholder="请选择景点状态" style="width: 190px">
              <el-option :value="0" label="开放" />
              <el-option :value="1" label="休息" />
              <el-option :value="1" label="关闭" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item>
            <el-button type="primary" icon="search" @click="getTableData()"> 搜索 </el-button>
            <el-button icon="refresh" @click="resetSearch"> 清空 </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row>
      <el-button v-auth="'attraction:save'" type="primary" icon="plus" @click="openEdit(null)">添加景点</el-button>
      <el-button
        v-auth="'attraction:delete'"
        type="danger"
        icon="delete"
        @click="handleRemove(state.selectionIds)"
        :disabled="state.selectionIds.length < 1"
        >批量删除</el-button
      >
    </el-row>

    <el-table
      class="mt10"
      :loading="state.loading"
      element-loading-text="正在努力加载数据中..."
      :data="state.page.records"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" fixed="left" width="55" />
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="name" label="景点名称" min-width="120" sortabe show-overflow-tooltip />
      <el-table-column prop="imageUrl" label="景点图片" min-width="120">
        <template #default="{ row }">
          <el-image
            style="width: 100px; height: 60px"
            :src="row.imageUrl"
            :preview-src-list="[row.imageUrl]"
            :preview-teleported="true"
          />
        </template>
      </el-table-column>
      <el-table-column prop="address" label="景点地址" min-width="120" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" min-width="80">
        <template #default="{ row }">
          <el-tag type="success" v-if="row.status === 0" effect="plain">开放</el-tag>
          <el-tag type="warning" v-if="row.status === 1" effect="plain">休息</el-tag>
          <el-tag type="danger" v-if="row.status === 2" effect="plain">关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="120" sortable show-overflow-tooltip />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-link
            type="primary"
            icon="view"
            @click="router.push({ name: 'AttractionDetail', params: { id: row.id } })"
          >
            查看
          </el-link>
          <el-divider v-auth="'attraction:update'" direction="vertical" />
          <el-link v-auth="'attraction:update'" type="success" icon="edit" @click="openEdit(row)">编辑 </el-link>
          <el-divider v-auth="'attraction:delete'" direction="vertical" />
          <el-link v-auth="'attraction:delete'" type="danger" icon="remove" @click="handleRemove([row.id])"
            >删除
          </el-link>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="mt10"
      :current-page="state.page.current"
      :page-size="state.page.size"
      :total="state.page.total"
      :page-sizes="[1, 3, 6, 9, 12, 15, 18]"
      layout="total, sizes, ->, prev, pager, next, jumper"
      background
      @current-change="getTableData"
      @size-change="handleSizeChange"
    />

    <el-dialog v-model="state.showEdit" :title="state.dialogTitle" @close="handleClose">
      <el-form ref="attractionFormRef" :model="state.attractionForm" :rules="state.attractionRules" label-width="100px">
        <el-row>
          <el-col>
            <el-form-item label="景点名称" prop="name">
              <el-input v-model="state.attractionForm.name" placeholder="请输入景点名称" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="景点图片" prop="imageUrl">
              <div class="profile-avatar">
                <el-upload
                  name="file"
                  :action="state.fileUploadApi"
                  :headers="state.fileHeaders"
                  :show-file-list="false"
                  :on-success="handleSuccess"
                  :before-upload="beforeUpload"
                >
                  <el-avatar shape="square" :size="150" :src="state.attractionForm.imageUrl" />
                </el-upload>
              </div>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="景点状态" prop="status">
              <el-select
                v-model="state.attractionForm.status"
                clearable
                placeholder="请选择景点状态"
                style="width: 190px"
              >
                <el-option :value="0" label="开放" />
                <el-option :value="1" label="休息" />
                <el-option :value="1" label="关闭" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="景点地址" prop="address">
              <el-input type="textarea" :rows="2" v-model="state.attractionForm.address" placeholder="请输入景点地址" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="景点描述" prop="description">
              <el-input
                type="textarea"
                :rows="3"
                v-model="state.attractionForm.description"
                placeholder="请输入景点描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="state.showEdit = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<style lang="scss" scoped>
.profile-avatar {
  text-align: center;
  margin-bottom: 20px;

  :deep(.el-upload) {
    display: inline-block;
  }

  .el-avatar {
    cursor: pointer;

    &:hover {
      opacity: 0.8;
    }
  }
}
</style>
